package cn.flying.base.sys.configuration.shiro;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AccountException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import cn.flying.base.common.constants.Constants;
import cn.flying.base.sys.configuration.exception.CaptchaException;
import cn.flying.base.sys.domain.SysUser;
import cn.flying.base.sys.domain.SysUserRole;
import cn.flying.base.sys.service.SysUserService;

/**
 * @description: shiro 认证与授权
 * @author: lvyong
 * @date: 2022年05月22日 08:10
 * @version: 1.0
 */
public class ShiroRealm extends AuthorizingRealm {

    private static final Logger LOGGER = LoggerFactory.getLogger(ShiroRealm.class);

    @Autowired
    private SysUserService sysUserService;

    /**
     * 授权
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        LOGGER.info("--------------授权验证方法-------------------");
        String username = (String) SecurityUtils.getSubject().getPrincipal();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //获得该用户角色
        SysUser sysUser = sysUserService.findUserByUsername(username);
        List<SysUserRole> roleList = sysUserService.getUserRoleList(sysUser.getUserId());
        Set<String> roles = roleList.stream().map(role -> role.getRoleId()).collect(Collectors.toSet());
        //设置该用户拥有的角色
        info.setRoles(roles);
        return info;
    }

    /**
     * 认证 鉴权
     *
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        LOGGER.info("--------------身份验证方法-------------------");
        CaptchaUsernamePasswordToken token = (CaptchaUsernamePasswordToken) authenticationToken;
        Session session = SecurityUtils.getSubject().getSession();
        String code = (String) session.getAttribute(Constants.SESSION_CAPTCHA_CODE);
        String captcha = token.getCaptcha();
        if (captcha == null) {
            throw new CaptchaException("验证码不能为空！");
        }
        if (!captcha.equalsIgnoreCase(code)) {
            throw new CaptchaException("验证码错误！");
        }
        String username = (String) token.getPrincipal();
        SysUser user = sysUserService.findUserByUsername(username);
        if (null == user) {
            throw new AccountException("用户不存在！");
        }
        session.setAttribute(Constants.TENANT_ID, user.getTenantId());
        return new SimpleAuthenticationInfo(username, user.getPassword(), ByteSource.Util.bytes(username), getName());
    }
}
